package drds.binlog.binlog_event.event.unimportance;

import drds.binlog.binlog_event.LogByteBlock;
import drds.binlog.binlog_event.event.FormatDescriptionLogEvent;
import drds.binlog.binlog_event.event.LoadLogEvent;
import drds.binlog.binlog_event.event.LogHeader;
import drds.binlog.common.Authors;
import drds.common.Author;
import lombok.Getter;
import lombok.Setter;

/**
 * Create_file_log_event.
 */
@Author(name = Authors.LI_YANG)
public final class CreateFileLogEvent extends LoadLogEvent
{

    /* CF = "Create File" */
    public static final int cf_file_id_offset = 0;
    public static final int cf_data_offset = FormatDescriptionLogEvent.create_file_header_length;
    @Setter
    @Getter
    protected LogByteBlock logByteBlock;
    @Setter
    @Getter
    protected int logByteBlockLength;
    @Setter
    @Getter
    protected long fileId;
    @Setter
    @Getter
    protected boolean initedFromOld;

    public CreateFileLogEvent(LogHeader logHeader, LogByteBlock logByteBlock, FormatDescriptionLogEvent formatDescriptionLogEvent)
    {
        super(logHeader, logByteBlock, formatDescriptionLogEvent);

        final int commonHeaderLength = formatDescriptionLogEvent.commonHeaderLength;
        final int loadEventHeaderLength = formatDescriptionLogEvent.postHeaderLengths[load_event - 1];
        final int createFileEventHeaderLength = formatDescriptionLogEvent.postHeaderLengths[create_file_event - 1];

        copyLogEvent(logByteBlock,
                ((logHeader.logType == load_event) ?//
                        (loadEventHeaderLength + commonHeaderLength) //
                        : (commonHeaderLength + loadEventHeaderLength + createFileEventHeaderLength)),//
                formatDescriptionLogEvent);

        if (formatDescriptionLogEvent.binlogVersion != 1)
        {
            fileId = logByteBlock.getLittleEndian4UnsignedLong(commonHeaderLength + loadEventHeaderLength + cf_file_id_offset);
            /*
             * Note that it's ok to use get_data_size() below, because it is
             * computed with values we have already read from this event
             * (because we called copy_log_event()); we are not using slave's
             * format info to decode master's format, we are really using
             * master's format info. Anyway, both formats should be identical
             * (except the common_header_len) as these Load events are not
             * changed between 4.0 and 5.0 (as logging of LOAD DATA INFILE does
             * not use Load_log_event in 5.0).
             */
            logByteBlockLength = logByteBlock.limit() - logByteBlock.index$originIndex();
            this.logByteBlock = logByteBlock.duplicateByIndex(logByteBlockLength);
        } else
        {
            initedFromOld = true;
        }
    }

    public final byte[] getData()
    {
        return logByteBlock.getBytesByIndex();
    }
}
